from flask import Blueprint, jsonify, session
from werkzeug.security import generate_password_hash
from easyRead.extensions import mail, db
from flask_mail import Message
from flask import request, make_response
import string
import random
from .forms import RegisterForm
from .forms import EmailForm
from easyRead.models import User

bp = Blueprint("register", __name__, url_prefix="/users")

@bp.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        message = "用户请求注册，跳转至注册页面！"
    else:
        # 验证用户提交的邮箱和验证码是否对应且正确
        # 表单验证：flask-wtf: wtforms
        form = RegisterForm(request.form)
        if form.validate():
            id = form.id.data
            email = form.email.data
            nickname = form.nickname.data
            password = form.password.data
            phone = form.phone.data
            user = User(id=id, nickname=nickname, password=generate_password_hash(password), email=email, level="user", phone=phone)
            db.session.add(user)
            db.session.commit()
            message = "注册成功，返回登录页面！"
        else:
            message = form.errors
    return make_response(jsonify(message))

# 向用户邮箱发送验证码，并把验证码存入session
@bp.route("/captcha", methods=['POST'])
def get_email_captcha():
    form = EmailForm(request.form)
    if form.validate():
        email = form.email.data
        captcha = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        message = Message(subject="easyRead注册验证码", recipients=[email], body=f"您的验证码是:{captcha}")
        mail.send(message)
        session['captcha'] = captcha
        return make_response(jsonify("用户邮箱接收验证码"))
    else:
        return make_response(jsonify(form.errors))